package com.anlu.base;

import lombok.extern.slf4j.Slf4j;

import static com.anlu.base.RemoteServiceStatus.FAILURE;
import static java.lang.Thread.sleep;

@Slf4j
public class ServiceAmbassador  implements RemoteServiceInterface{


    private static final int RETRIES = 3;
    private static final int DELAY_MS = 3000;

    public ServiceAmbassador() {
    }

    @Override
    public long doRemoteFunction(int value) {
        return safeCall(value);
    }

    private long checkLatency(int value) {
        var startTime = System.currentTimeMillis();
        var result = RemoteService.getRemoteService().doRemoteFunction(value);
        var timeTaken = System.currentTimeMillis() - startTime;

        log.info("Time taken (ms): {}", timeTaken);
        return result;
    }

    private long safeCall(int value){
        var retries = 0;
        var result = FAILURE.getRemoteServiceStatusValue();
        for (int i = 0; i < RETRIES; i++) {
            if (retries >= RETRIES) {
                return FAILURE.getRemoteServiceStatusValue();
            }
            if((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()){
                log.info("Failed to reach remote: ({})", i + 1);
                retries++;
                try{
                    sleep(DELAY_MS);
                }catch (InterruptedException e){
                    log.error("Thread sleep state interrupted", e);
                    Thread.currentThread().interrupt();
                }
            }else{
                break;
            }
        }
        return result;
    }
}
